<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable @keyup.enter.native="handleQuery">
          <el-option
            v-for="dict in dict.type.mall_brand_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQueryForm">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- plain是否朴素按钮-->
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['prod:brand:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- plain是否朴素按钮-->
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleEdit" :disabled="isNotSelectedOne"
                   v-hasPermi="['prod:brand:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- plain是否朴素按钮-->
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete"
                   :disabled="isNotSelectedAny"
                   v-hasPermi="['prod:brand:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- plain是否朴素按钮-->
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['prod:brand:export']">导出
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="brandList"
      style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column
        prop="id"
        label="ID"
        align="center">
      </el-table-column>
      <el-table-column
        prop="name"
        label="名称"
        align="center">
      </el-table-column>
      <el-table-column
        align="center"
        prop="icon"
        width="100"
        label="图标">
        <template slot-scope="scope">
          <image-preview :src="scope.row.icon" width="50" height="50"></image-preview>
        </template>
      </el-table-column>
      <el-table-column
        prop="weight"
        label="权重"
        align="center">
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mall_brand_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="updateTime"
        align="center"
        label="更新时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        align="center"
        label="创建时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="address"
        align="center"
        label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)"
                     v-hasPermi="['prod:brand:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete"
                     v-hasPermi="['prod:brand:remove']" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改品牌对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="dataForm" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="dataForm.name" placeholder="请输入名称" ref="dataFormNameRef"/>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <image-upload :limit=1 :fileSize=120 v-model="dataForm.icon"></image-upload>
        </el-form-item>
        <el-form-item label="权重" prop="weight">
          <el-input v-model="dataForm.weight" placeholder="请输入权重"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dataForm.status">
            <el-radio
              v-for="dict in dict.type.mall_brand_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getBrandList"
    />

  </div>
</template>

<script>
import {listBrand, addBrand, deleteBrand, editBrand, updateBrand, checkExisting} from "@/api/prod/brand";


export default {
  name: "brand",
  dicts: ['mall_brand_status'],
  data() {
    let checkWeightMax = (rule, value, callback) => {
      if (value > 0 && value <= 100) {
        callback()
      } else {
        callback('权重值要小于等于100并且大于0!')
      }
    }

    let checkDuplicateNames = async(rule, value, callback) => {
      let name = value;
      let id = this.dataForm.id;
      let pathParamsStr = name;
      if(id !== undefined && id !== null && id !== 0){
        pathParamsStr = pathParamsStr + "/" + id;
      }else{
        pathParamsStr = pathParamsStr + "/" + 0;
      }

      let res = await checkExisting(pathParamsStr)
      let isExisting = res.data;
      isExisting ? callback("已存在相同名称") : callback()
    }

    return {
      ids: [],
      // 非单个禁用, 默认禁用
      isNotSelectedOne: true,
      // 非多个禁用
      isNotSelectedAny: true,
      queryForm: {
        name: undefined,
        id: undefined
      },
      brandList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined
      },
      total: 0,
      loading: false,
      title: '',
      open: false,
      dataForm: {
        name: undefined,
        icon: undefined,
        weight: undefined,
        status: ""
      },
      rules: {
        name: [
          {required: true, message: "名称不能为空!", trigger: "blur"},
          {validator: checkDuplicateNames, trigger: "blur"}
        ],
        weight: [
          {required: true, message: "权重不能为空!", trigger: "blur"},
          {validator: checkWeightMax, trigger: "blur"}
        ],
        status: [
          {required: true, message: "状态不能为空!", trigger: "blur"}
        ]
      }

    }
  },
  created() {
    this.getBrandList();
  },
  methods: {
    getBrandList() {
      this.loading = true;
      listBrand(this.queryParams).then(response => {
        this.brandList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 表单重置
    resetDataForm() {
      this.dataForm = {
        name: undefined,
        icon: undefined,
        weight: undefined,
        status: ""
      };
      this.resetForm("form");
    },

    handleAdd() {
      this.resetDataForm();
      this.open = true;
      this.title = '新增品牌';
      this.focus("dataFormNameRef");
    },
    handleEdit(row) {
      this.resetDataForm();
      const brandId = row.id || this.ids;
      editBrand(brandId).then(response => {
        this.dataForm.id = response.data.id;
        this.dataForm.name = response.data.name;
        this.dataForm.icon = response.data.icon;
        this.dataForm.status = response.data.status + "";
        this.dataForm.weight = response.data.weight;


        this.open = true;
        this.title = '修改品牌';
        this.focus("dataFormNameRef");
      })
    },

    handleDelete(row) {
      const brandId = row.id || this.ids;
      this.$modal.confirm('是否确认删除ID为"' + brandId + '"的数据项？').then(function () {
        return deleteBrand(brandId);
      }).then(() => {
        this.getBrandList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1;

      this.getBrandList();
    },
    resetQueryForm() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleExport() {
      this.download('prod/brand/export', {
        ...this.queryParams
      }, `unit_${new Date().getTime()}.xlsx`)
    },
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        if (this.dataForm.id) {
          updateBrand(this.dataForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getBrandList();
          })
        } else {
          addBrand(this.dataForm).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getBrandList();
          });
        }
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)

      this.isNotSelectedOne = selection.length != 1
      this.isNotSelectedAny = !selection.length
    },
  }
}
</script>

<style scoped>

</style>
